﻿#include "stdafx.h"
#include "./luaex.h"
#include "./luaobj.h"

LuaObj::LuaObj()
: m_addr(-1)
, m_luaState(LuaEx::GetInstance().GetLuaState())
{
	::InitializeCriticalSection(&m_csThreadSafe);
}

LuaObj::~LuaObj()
{
	::DeleteCriticalSection(&m_csThreadSafe);
    luaL_unref(LuaEx::GetInstance().GetLuaState(), LUA_REGISTRYINDEX, m_addr);
	m_addr = -1;
}

void LuaObj::InitObj(int addr)
{
	m_addr = addr;
}

void LuaObj::CloneObj(int addr)
{
	lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, addr);
	luaL_ref(m_luaState, LUA_REGISTRYINDEX);

	m_addr = addr;
}

int LuaObj::GetObj()
{
    return m_addr;
}

void LuaObj::PushObj(lua_State* luaState)
{
	::EnterCriticalSection(&m_csThreadSafe);
	lua_rawgeti(luaState, LUA_REGISTRYINDEX, m_addr);
	::LeaveCriticalSection(&m_csThreadSafe);
}